<template>
  <div class="role-list-container">
    <el-card class="search-card">
      <el-form 
        :inline="true" 
        :model="searchForm" 
        class="search-form"
      >
        <el-form-item label="角色名称">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入角色名称" 
            prefix-icon="el-icon-search" 
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            icon="el-icon-search" 
            @click="onSearch"
          >
            查询
          </el-button>
          <el-button 
            icon="el-icon-refresh" 
            @click="resetSearch"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <div class="button-group">
        <el-button v-if="hasPermission('/system/role/add')"
          type="primary" 
          icon="el-icon-plus" 
          @click="addRole"
        >
          新增角色
        </el-button>
        <el-button v-if="hasPermission('/system/role/update')"
          type="warning" 
          icon="el-icon-edit" 
          :disabled="multipleSelection.length !== 1" 
          @click="editRole"
        >
          编辑角色
        </el-button>
        <el-button v-if="hasPermission('/system/role/delete')"
          type="danger" 
          icon="el-icon-delete" 
          :disabled="multipleSelection.length === 0" 
          @click="deleteRole"
        >
          删除角色
        </el-button>
      </div>
      
      <el-table
        ref="roleTable"
        :data="tableData"
        style="width: 100%"
        border
        stripe
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column 
          type="selection" 
          width="55" 
        />
        <el-table-column 
          prop="name" 
          label="角色名称" 
          width="180" 
        />
        <el-table-column 
          label="操作" 
          width="150" 
          fixed="right"
        >
          <template #default="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="editSingleRole(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              style="color: #F56C6C;" 
              @click="deleteSingleRole(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          :page-sizes="[2, 10, 20, 50, 100]"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { getRoleList, deleteRole } from '@/api/role'
import { hasPermission } from '@/utils/permissions'

export default {
  data() {
    return {
      searchForm: {
        name: ''
      },
      tableData: [],
      currentPage: 1,
      pageSize: 2,
      total: 0,
      multipleSelection: []
    }
  },
  created() {
    console.log('当前页:', this.currentPage)
    console.log('页面大小:', this.pageSize)
    console.log('总数:', this.total)
    this.fetchData()
  },
  methods: {
    async fetchData() {
      try {
        const { data } = await getRoleList({
          page: this.currentPage,
          rows: this.pageSize,
          name: this.searchForm.name
        })
        this.tableData = data.data.rows
        this.total = data.data.total
      } catch (error) {
        console.error('获取角色列表失败:', error)
        this.$message.error('获取角色列表失败')
      }
    },
    onSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm.name = ''
      this.onSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    addRole() {
      this.$router.push('/roles/add')
    },
    editRole() {
      if (this.multipleSelection.length !== 1) {
        this.$message.warning('请选择一条记录进行编辑')
        return
      }
      const roleId = this.multipleSelection[0].id
      this.$router.push(`/roles/edit/${roleId}`)
    },
    async deleteRole() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录')
        return
      }
      try {
        await this.$confirm('确认删除选中的角色?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const ids = this.multipleSelection.map(row => row.id)
        await deleteRole(ids)
        this.$message.success('删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除角色失败:', error)
          this.$message.error('删除角色失败')
        }
      }
    },
    async deleteSingleRole(row) {
      try {
        await this.$confirm(`确认删除角色 ${row.name}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteRole([row.id])
        this.$message.success('删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除角色失败:', error)
          this.$message.error('删除角色失败')
        }
      }
    },
    editSingleRole(row) {
      this.$router.push(`/roles/edit/${row.id}`)
    },
    hasPermission(permission) {
      return hasPermission(this.$store, permission);
    }
  }
}
</script>

<style scoped>
.role-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.table-card {
  margin-top: 20px;
}

.button-group {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>